/**
 * AI服务请求工具
 * 支持开发环境和生产环境的自动切换
 * 提供统一的错误处理和重试机制
 */

class AIServiceClient {
  constructor() {
    this.baseURL = this.getBaseURL()
    this.maxRetries = 3
    this.retryDelay = 1000 // 1秒
  }

  /**
   * 获取基础URL
   */
  getBaseURL() {
    // 开发环境使用代理，生产环境直接使用后端地址
    if (import.meta.env.DEV) {
      return '' // 使用相对路径，通过Vite代理
    } else {
      return import.meta.env.VITE_AI_LEARNING_API || 'http://47.113.221.252:8107'
    }
  }

  /**
   * 构建完整URL
   */
  buildURL(path) {
    return `${this.baseURL}${path}`
  }

  /**
   * 延迟函数
   */
  delay(ms) {
    return new Promise(resolve => setTimeout(resolve, ms))
  }

  /**
   * 重试机制
   */
  async retryRequest(requestFunc, retries = this.maxRetries) {
    try {
      return await requestFunc()
    } catch (error) {
      if (retries > 0 && this.isRetryableError(error)) {
        console.log(`请求失败，${this.retryDelay}ms后重试，剩余重试次数：${retries}`)
        await this.delay(this.retryDelay)
        return this.retryRequest(requestFunc, retries - 1)
      }
      throw error
    }
  }

  /**
   * 判断是否需要重试的错误
   */
  isRetryableError(error) {
    return !error.response || error.response.status >= 500
  }

  /**
   * 流式请求（用于AI聊天）
   */
  async streamRequest(path, params = {}) {
    const url = this.buildURL(path)
    const queryString = new URLSearchParams(params).toString()
    const fullUrl = queryString ? `${url}?${queryString}` : url

    return this.retryRequest(async () => {
      const response = await fetch(fullUrl, {
        method: 'GET',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${this.getToken()}`
        }
      })

      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`)
      }

      return response
    })
  }

  /**
   * 获取token
   */
  getToken() {
    return localStorage.getItem('token') || ''
  }

  /**
   * 处理流式响应
   */
  async processStreamResponse(response, onChunk, onComplete, onError) {
    const reader = response.body.getReader()
    const decoder = new TextDecoder('utf-8')
    let accumulatedContent = ''

    try {
      while (true) {
        const { done, value } = await reader.read()
        
        if (done) {
          // 流结束，处理最终内容
          let finalContent = accumulatedContent
            .replace(/\[DONE\]/g, '')
            .replace(/data:\s*\[DONE\]/g, '')
            .trim()
          
          if (onComplete) {
            onComplete(finalContent)
          }
          break
        }

        const chunk = decoder.decode(value, { stream: true })
        let processedChunk = chunk.replace(/\[DONE\]/g, '')

        if (processedChunk.startsWith('ERROR:')) {
          if (onError) {
            onError(processedChunk.substring(6))
          }
          break
        }

        accumulatedContent += processedChunk
        
        if (onChunk) {
          onChunk(accumulatedContent)
        }
      }
    } catch (error) {
      console.error('流式读取错误:', error)
      if (onError) {
        onError('流式读取失败: ' + error.message)
      }
    } finally {
      reader.releaseLock()
    }
  }
}

// 创建单例实例
const aiService = new AIServiceClient()

export default aiService

// 便捷函数
export const aiStreamRequest = (path, params, callbacks) => {
  return aiService.streamRequest(path, params)
    .then(response => {
      return aiService.processStreamResponse(
        response,
        callbacks.onChunk,
        callbacks.onComplete,
        callbacks.onError
      )
    })
}